/*
 * ArCoLIVE - Live Internet Videoconference Environment
 * Information Technology Departament - Federal University of Alagoas - Brazil
 *
 * Copyright (C) 2005 Leandro Melo de Sales (leandro@labpesquisas.tci.ufal.br)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package br.ufal.tci.nexos.arcolive.service.connection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Stack;

import br.ufal.tci.nexos.arcolive.events.ParticipantConnectionEvent;
import br.ufal.tci.nexos.arcolive.exception.ArCoLIVECannotCreateConnectionException;
import br.ufal.tci.nexos.arcolive.logger.ArCoLIVELogRepository;


/**
 * CLASSNAME.java
 *
 * CLASS DESCRIPTION
 *
 * @see CLASSNAME
 *
 * @author <a href="mailto:felipe@labpesquisas.tci.ufal.br">Felipe Barros Pontes</a>.
 * @author <a href="mailto:leandro@labpesquisas.tci.ufal.br">Leandro Melo de Sales</a>.
 * @since 0.1
 * @version 0.1
 *
 * <p><b>Revisions:</b>
 *
 * <p><b>yyyymmdd USERNAME:</b>
 * <ul>
 * <li> VERSION
 * </ul>
 */
public class Connection extends Thread {

	private PrintWriter output;
	private BufferedReader input;
	private Socket socket;
	private boolean listeningConnection = true;
	private Set listeners;
	private Stack sendMessageStackControl;
	
	public Connection(Socket socket) throws ArCoLIVECannotCreateConnectionException {
		try {
			this.output = new PrintWriter(socket.getOutputStream(), true);
			this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			this.sendMessageStackControl = new Stack();
		} catch (IOException e) {
			throw new ArCoLIVECannotCreateConnectionException("Error while trying to create connection", e);
		}
		
		this.socket = socket;
		this.listeners = new HashSet();
	}
	
	public void listen() {
		this.start();
	}
	
	public void addListener(ConnectionListener pnsl) {
		this.listeners.add(pnsl);
	}	
	
	public synchronized void sendMessage(String message) {
		this.sendMessageStackControl.push("");
		this.output.println(message);
		this.sendMessageStackControl.pop();
	}
	
	public Socket getSocket() {
		return this.socket;
	}
	
	public InetAddress getInetAddress() {
		return this.socket.getInetAddress();
	}
	
	protected synchronized void close() {
		try {
			while (!this.sendMessageStackControl.isEmpty()) {
				System.out.println(this.sendMessageStackControl.size());
				Thread.sleep(3000);
			}
			this.listeningConnection = false;
			this.socket.close();
		} catch (Exception e) { }
	}
	
	/*public void run() {
		System.out.println("ENTROU EM RUN DE CONNECTION...");
		String message;
		try {
			while (((message = this.input.readLine()) != null) && this.listeningConnection) {
				System.out.println("ENTROU EM WHIOE DE CONNECTION...");
				ArCoLIVELogRepository.getInstance().log("A client request has arrived from " + this + ". The server will notify the ServiceBroker");
				ParticipantConnectionEvent ccpe = new ParticipantConnectionEvent(this, message);
				this.notifyConnectionParticipantEvent(ccpe);
			}
		} catch (IOException e) { }
		ArCoLIVELogRepository.getInstance().log("Participant thread died " + this);
	}*/
	
	public void run() {
		System.out.println("ENTROU EM RUN DE CONNECTION...");
		String message;
		ArCoLIVELogRepository.getInstance().log("A client request has arrived from " + this + ". The server will notify the ServiceBroker");
		ParticipantConnectionEvent ccpe = new ParticipantConnectionEvent(this, "700#requestId=1#commandId=701#serviceId=1#instanceId=1");
		this.notifyConnectionParticipantEvent(ccpe);
	}

	
	private void notifyConnectionParticipantEvent(ParticipantConnectionEvent event) {
		for (Iterator iter = this.listeners.iterator(); iter.hasNext();) {
			((ConnectionListener)iter.next()).connectionParticipantEvent(event);
		}
	}	
}
